<template>
  <div class="layout-container">
    <div class="layout-container-table">
      <div style="margin: 0 0 5px 0">
        <el-button type="primary" :icon="Plus" @click="add">新增</el-button>
      </div>
      <el-table
        :data="tableData.list"
        style="width: 100%"
        height="380"
        max-height="100%"
        v-loading="loading"
        element-loading-text="Loading..."
        border
        stripe
      >
        <el-table-column
          type="index"
          width="75"
          label="序号"
          align="center"
          fixed
        />
        <el-table-column
          prop="tableCode"
          label="表格编码"
          width="200"
          align="center"
        />
        <el-table-column
          prop="tableNameStr"
          label="表格名称"
          width="200"
          align="center"
        >
          <template #default="scope">
            <div class="modality" @click="selectColumn(scope.row)">
              {{ scope.row.tableNameStr }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="tableSize"
          label="表格尺寸"
          width="120"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="status"
          label="是否启用"
          width="140"
          align="center"
        >
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              size="small"
              active-text="开启"
              inactive-text="关闭"
            />
          </template>
        </el-table-column>

        <el-table-column
          prop="stripe"
          label="斑马纹"
          width="140"
          align="center"
        >
          <template #default="scope">
            <el-switch
              v-model="scope.row.stripe"
              size="small"
              active-text="开启"
              inactive-text="关闭"
            />
          </template>
        </el-table-column>
        <el-table-column prop="border" label="边框" width="140" align="center">
          <template #default="scope">
            <el-switch
              v-model="scope.row.border"
              size="small"
              active-text="开启"
              inactive-text="关闭"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="round"
          label="圆角表格"
          width="140"
          align="center"
        >
          <template #default="scope">
            <el-switch
              v-model="scope.row.round"
              size="small"
              active-text="开启"
              inactive-text="关闭"
            />
          </template>
        </el-table-column>

        <!-- <el-table-column
          prop="maxHeight"
          label="最大高度"
          width="120"
          align="center"
        /> -->
        <el-table-column
          prop="autoResize"
          label="动态宽度"
          width="140"
          align="center"
        >
          <template #default="scope">
            <el-switch
              v-model="scope.row.autoResize"
              size="small"
              active-text="开启"
              inactive-text="关闭"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="height"
          label="表格高度"
          width="120"
          align="center"
        />
        <el-table-column
          prop="createId"
          label="创建人"
          width="130"
          align="center"
        />
        <el-table-column
          prop="createTime"
          label="创建时间"
          width="200"
          align="center"
        />
        <el-table-column label="操作" width="120" align="center" fixed="right">
          <template #default="scope">
            <div class="modality" @click="otherConfigurations(scope.row)">
              其他配置
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="page">
        <!-- 分页 -->
        <Paging
          :total="total"
          :currentPage.sync="page.mount"
          :pageSize.sync="page.size"
          @pagination="handlePageChange"
        ></Paging>
      </div>
    </div>

    <!-- 添加弹框 -->
    <el-dialog
      v-model="dialogVisible"
      title="新增"
      width="50%"
      draggable
      :before-close="handleClose"
    >
      <el-form
        label-width="120"
        :model="formInline"
        :rules="rules"
        ref="ruleFormRef"
        class="demo-form-inline"
      >
        <el-form-item label="数据表名称:" prop="sqlTableNameList">
          <el-select
            v-model="formInline.sqlTableNameList"
            filterable
            clearable
            multiple
            placeholder="请选择数据库表名"
            style="width: 100%"
          >
            <el-option
              v-for="item in tableOptionsList"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="表格编码:" prop="tableCode">
          <el-input
            v-model="formInline.tableCode"
            placeholder="请输入表格编码"
          />
        </el-form-item>
        <el-form-item label="表格名称:" prop="tableNameStr">
          <el-input
            v-model="formInline.tableNameStr"
            placeholder="请输入表格名称"
          />
        </el-form-item>
        <el-form-item label="表格高度:" prop="height">
          <el-input v-model="formInline.height" placeholder="请输入高度" />
        </el-form-item>
        <!-- <el-form-item label="最高高度:" prop="maxHeight">
        <el-input v-model="formInline.maxHeight" placeholder="请输入最高高度" />
      </el-form-item> -->
        <el-form-item label="表格大小:">
          <el-radio-group v-model="formInline.tableSize">
            <el-radio-button label="medium" />
            <el-radio-button label="small" />
            <el-radio-button label="mini" />
          </el-radio-group>
        </el-form-item>
        <el-form-item label="斑马纹:">
          <el-switch
            v-model="formInline.stripe"
            active-text="开启"
            inactive-text="关闭"
          />
        </el-form-item>
        <el-form-item label="边框:">
          <el-switch
            v-model="formInline.border"
            active-text="开启"
            inactive-text="关闭"
          />
        </el-form-item>
        <el-form-item label="圆角边框:">
          <el-switch
            v-model="formInline.round"
            active-text="开启"
            inactive-text="关闭"
          />
        </el-form-item>
        <el-form-item label="sql:">
          <el-input
            v-model="formInline.fromSql"
            type="textarea"
            placeholder="请输入sql"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="描述:">
          <el-input
            v-model="formInline.describeStr"
            type="textarea"
            placeholder="请输入描述"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="dialogOk(ruleFormRef)">
            确认
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 其他配置 抽屉 -->
    <el-drawer v-model="drawer" title="扩展配置" size="70%">
      <el-tabs
        type="border-card"
        v-loading="loadingDrawer"
        element-loading-text="加载中..."
      >
        <el-tab-pane label="分页配置项">
          <div class="switch-config">
            <div class="switch-config-item">
              <div>是否启用</div>
              <div>
                <el-switch
                  v-model="extend.config.pagerConfig.enabled"
                  size="default"
                />
              </div>
            </div>
            <div class="switch-config-item">
              <div style="flex: 9.9">
                <span>配置代码</span>
                <div calss="textareaCls">
                  <codemirror
                    v-model="extend.config.pagerConfig.codeConfigForm"
                    :style="{ height: '300px', width: '100%' }"
                    :autofocus="true"
                    :tabSize="2"
                    :extensions="extensions"
                  ></codemirror>
                </div>
              </div>
              <div style="flex: 0.1"></div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="数据代理配置项">
          <div class="switch-config">
            <div class="switch-config-item">
              <div>是否启用</div>
              <div>
                <el-switch
                  v-model="extend.config.proxyConfig.enabled"
                  size="default"
                />
              </div>
            </div>
            <div class="switch-config-item">
              <div style="flex: 9.9">
                <span>配置代码</span>
                <div calss="textareaCls">
                  <codemirror
                    v-model="extend.config.proxyConfig.codeConfigForm"
                    :style="{ height: '400px', width: '100%' }"
                    :autofocus="true"
                    :tabSize="2"
                    :extensions="extensions"
                  ></codemirror>
                </div>
              </div>
              <div style="flex: 0.1"></div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="行/列 配置项">
          <div class="switch-config">
            <div class="switch-config-item">
              <div>是否启用</div>
              <div>
                <el-switch
                  v-model="extend.config.rowConfig.enabled"
                  size="default"
                />
              </div>
            </div>
            <div class="switch-config-item">
              <div style="flex: 9.9">
                <span>行配置代码</span>
                <div calss="textareaCls">
                  <codemirror
                    v-model="extend.config.rowConfig.codeConfigForm"
                    :style="{ height: '250px', width: '100%' }"
                    :autofocus="true"
                    :tabSize="2"
                    :extensions="extensions"
                  ></codemirror>
                </div>
              </div>
              <div style="flex: 0.1"></div>
            </div>
          </div>
          <div class="switch-config">
            <div class="switch-config-item">
              <div>是否启用</div>
              <div>
                <el-switch
                  v-model="extend.config.columnConfig.enabled"
                  size="default"
                />
              </div>
            </div>
            <div class="switch-config-item">
              <div style="flex: 9.9">
                <span>列配置代码</span>
                <div calss="textareaCls">
                  <codemirror
                    v-model="extend.config.columnConfig.codeConfigForm"
                    :style="{ height: '250px', width: '100%' }"
                    :autofocus="true"
                    :tabSize="2"
                    :extensions="extensions"
                  ></codemirror>
                </div>
              </div>
              <div style="flex: 0.1"></div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="复选框配置项">
          <div class="switch-config">
            <div class="switch-config-item">
              <div>是否启用</div>
              <div>
                <el-switch
                  v-model="extend.config.checkboxConfig.enabled"
                  size="default"
                />
              </div>
            </div>
            <div class="switch-config-item">
              <div style="flex: 9.9">
                <span>复选框配置代码</span>
                <div calss="textareaCls">
                  <codemirror
                    v-model="extend.config.checkboxConfig.codeConfigForm"
                    :style="{ height: '250px', width: '100%' }"
                    :autofocus="true"
                    :tabSize="2"
                    :extensions="extensions"
                  ></codemirror>
                </div>
              </div>
              <div style="flex: 0.1"></div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="工具栏配置项">
          <div class="switch-config">
            <div class="switch-config-item">
              <div>是否启用</div>
              <div>
                <el-switch
                  v-model="extend.config.toolbarConfig.enabled"
                  size="default"
                />
              </div>
            </div>
            <div class="switch-config-item">
              <div style="flex: 9.9">
                <span>工具栏配置代码</span>
                <div calss="textareaCls">
                  <codemirror
                    v-model="extend.config.toolbarConfig.codeConfigForm"
                    :style="{ height: '250px', width: '100%' }"
                    :autofocus="true"
                    :tabSize="2"
                    :extensions="extensions"
                  ></codemirror>
                </div>
              </div>
              <div style="flex: 0.1"></div>
            </div>
          </div>
        </el-tab-pane>
        <el-tab-pane label="打印配置项">
          <div class="switch-config">
            <div class="switch-config-item">
              <div>是否启用</div>
              <div>
                <el-switch
                  v-model="extend.config.printConfig.enabled"
                  size="default"
                />
              </div>
            </div>
            <div class="switch-config-item">
              <div style="flex: 9.9">
                <span>打印配置代码</span>
                <div calss="textareaCls">
                  <codemirror
                    v-model="extend.config.printConfig.codeConfigForm"
                    :style="{ height: '250px', width: '100%' }"
                    :autofocus="true"
                    :tabSize="2"
                    :extensions="extensions"
                  ></codemirror>
                </div>
              </div>
              <div style="flex: 0.1"></div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>

      <template #footer>
        <div style="flex: auto">
          <el-button @click="cancelClick">取消</el-button>
          <el-button type="primary" @click="confirmClick">确认</el-button>
        </div>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
// 编辑代码
import { Codemirror } from "vue-codemirror";
import { javascript } from "@codemirror/lang-javascript";
import { oneDark } from "@codemirror/theme-one-dark";
import Paging from "@/components/basePage/packagePaging/index.vue";
import { isValidKey } from "@/utils/packaging/commonFun";
// 引入自定义请求库
import { postAction, getAction } from "@/utils/system/commonUse";
// 接受父组件事件
const emit = defineEmits(["introductionRow"]);
// 服务器地址
const url = reactive({
  addUrl: "/dynamic/dynamicTable/saveOrUpdate",
  getListUrl: "/dynamic/dynamicTable/queryDataByPage",
  getOptionsUrl: "/dynamic/metaTable/listTables",
  configurationUrl: "/dynamic/dynamicConfig/saveConfig",
  getConfigListUrl: "/dynamic/dynamicConfig/queryConfigByTableCode",
});

onMounted(() => {
  getList();
});
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  sqlTableNameList: [
    { required: true, message: "请选择数据库表名", trigger: "change" },
  ],
  tableCode: [{ required: true, message: "请填写表格编码", trigger: "blur" }],
  tableNameStr: [{ required: true, message: "请填写表名", trigger: "blur" }],
  height: [{ required: true, message: "请填写高度", trigger: "blur" }],
  // maxHeight: [{ required: true, message: "请填写最高高度", trigger: "blur" }],
});
// 表格数据
const tableData = reactive({ list: Array() });

const dialogVisible = ref(false);
// 加载中
const loading = ref(false);
// 抽屉加载
const loadingDrawer = ref(false);

const formInline = reactive({
  sqlTableNameList: [], //数据库表名
  tableCode: "", //表格编码
  tableNameStr: "", //表名
  describeStr: "", //描述
  tableSize: "medium", //表格大小
  stripe: true, //斑马纹
  height: "", //高度
  // maxHeight: "", //最高高度
  border: true, //最高高度
  round: true, //最高高度
  fromSql: "", //后端拼接的sql
});
// 选项
const tableOptionsList = ref(Array());

// 条数
const total = ref(0);
const page = reactive({
  size: 10, // 长度
  mount: 1, // 页码
});

// 分页器
const handlePageChange = (data: any) => {
  page.mount = data.currentPage;
  page.size = data.pageSize;
  getList();
};
const handleClose = (done: () => void) => {
  done();
};
/**
 * 查看列详情
 */
const selectColumn = (row: any) => {
  emit("introductionRow", row);
};
/***
 * 添加
 */
const add = () => {
  getOptionsList();
  dialogVisible.value = true;
};
/**
 * 获取数据
 */
const getList = () => {
  loading.value = true;
  postAction(url.getListUrl, page)
    .then((data: any) => {
      console.log("查询===>", data);
      if (data.code != 1000) {
        return ElMessage.error(data.msg);
      }
      total.value = data.data.count;
      tableData.list = data.data.data;
      loading.value = false;
    })
    .catch((err) => {
      console.log(err);
      ElMessage.error("获取数据失败");
      loading.value = false;
    });
};
/**
 * 获取数据库表名
 */
const getOptionsList = () => {
  postAction(url.getOptionsUrl)
    .then((data: any) => {
      console.log("getOptionsList===>", data);
      if (data.code != 1000) {
        return ElMessage.error(data.msg);
      }
      tableOptionsList.value = data.data;
    })
    .catch((err) => {
      console.log(err);
      ElMessage.error("获取数据失败");
    });
};

// 确认提交
const dialogOk = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate((valid, fields) => {
    if (!valid) {
      return;
    }
    console.log("提交");
    postAction(url.addUrl, formInline)
      .then((data: any) => {
        console.log("添加===>", data);
        if (data.code != 1000) {
          return ElMessage.error(data.msg);
        }
        ElMessage({
          message: data.msg,
          type: "success",
        });
        dialogVisible.value = false;
        getList();
      })
      .catch((err) => {
        console.log(err);
        ElMessage.error("新增失败");
      });
  });
};

// ============================================================抽屉配置==================================================================
// 控制抽屉显示隐藏
const drawer = ref(false);
// 扩展配置数据绑定
const extend = reactive({
  config: {
    // 分页
    pagerConfig: {
      // 是否启用
      enabled: true,
      // 代码编辑
      codeConfigForm: "",
      codeConfig: {},
    },
    // 数据代理配置项
    proxyConfig: {
      // 是否启用
      enabled: true,
      // 代码编辑
      codeConfigForm: "",
      codeConfig: {},
    },
    // 行代理配置项
    rowConfig: {
      // 是否启用
      enabled: true,
      // 代码编辑
      codeConfigForm: "",
      codeConfig: {},
    },
    // 列代理配置项
    columnConfig: {
      // 是否启用
      enabled: true,
      // 代码编辑
      codeConfigForm: "",
      codeConfig: {},
    },
    // 多选框配置项
    checkboxConfig: {
      // 是否启用
      enabled: true,
      // 代码编辑
      codeConfigForm: "",
      codeConfig: {},
    },
    // 工具栏配置项
    toolbarConfig: {
      // 是否启用
      enabled: true,
      // 代码编辑
      codeConfigForm: "",
      codeConfig: {},
    },
    // 打印配置项
    printConfig: {
      // 是否启用
      enabled: true,
      // 代码编辑
      codeConfigForm: "",
      codeConfig: {},
    },
  },
});

/**
 * 其他配置
 */
const otherConfigurations = (row: any) => {
  tableCode.value = row.tableCode;
  loadingDrawer.value = true;
  drawer.value = true;
  getAction(`${url.getConfigListUrl}/${row.tableCode}`)
    .then((data) => {
      extend.config = Object.assign(extend.config, data.data);
      console.log("===>", extend.config);
      loadingDrawer.value = false;
    })
    .catch((err) => {
      console.log("===>", err);
      loadingDrawer.value = false;
    });
};
// ============================代码编辑============================================
// 行id
const tableCode = ref("");
const extensions = [javascript(), oneDark];
// 关闭抽屉
const cancelClick = () => {
  drawer.value = false;
};
const confirmClick = () => {
  for (const extendKey in extend.config) {
    console.log(
      "extend.config[extendKey].codeConfigForm",
      extend.config[extendKey].codeConfigForm
    );

    extend.config[extendKey].codeConfig = eval(
      "(" + extend.config[extendKey].codeConfigForm + ")"
    );

    // extend[extendKey].codeConfig = JSON.parse(
    //   extend[extendKey].codeConfigForm.replace(/\s/g, "")
    // );
  }
  postAction(
    `${url.configurationUrl}?tableCode=${tableCode.value}`,
    extend.config
  )
    .then((data: any) => {
      console.log("配置===>", data);
      if (data.code != 1000) {
        return ElMessage.error(data.msg);
      }
    })
    .catch((err) => {
      console.log(err);
      ElMessage.error("配置失败");
    });
  drawer.value = false;
};
</script>

<style lang="scss" scoped>
.layout-container {
  height: 100%;
  margin: 0 0 0 10px;
  width: calc(100% - 10px);
  &-table {
    margin: 3px;
  }
}
.modality {
  cursor: pointer;
  color: #1890ff;
}

.switch-config .switch-config-item {
  display: flex;
  justify-content: space-between;
  border-bottom: 1px dashed rgb(238, 238, 238);
  padding: 10px 0px;
}
.textareaCls {
  border: 1px solid red;
  cursor: pointer !important;
  padding: 30px;
}
</style>
